<?php

namespace App\Http\Controllers\V1\Admin;

use App\Http\Controllers\V1\Api\BaseController;
use App\Models\V1\SysLoginLogs;
use Earnp\GoogleAuthenticator\GoogleAuthenticator;
use Illuminate\Http\Request;

class AuthController extends BaseController
{
    /**
     * 管理员登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $security_code=$request->input('security_code',"");

        //查询账号是否启用安全动态密码
        $credentials = $request->only(['username', 'password']);

        if (! $token = auth('box_admin')->attempt($credentials)) {

            return ajax_output(300,"用户名或密码错误");
        }

        $user=auth('box_admin')->user();

        //查询账号是否启用安全动态密码
        if($user->is_google_auth&&!GoogleAuthenticator::CheckCode($user->google_secret,$security_code)){
            return ajax_output(300,"安全动态密码验证失败");
        }

        //更新登录表token
        auth('box_admin')->user()->setRememberToken($token);
        //记录日志
        $loginlogs_model=new SysLoginLogs();
        $loginlogs_model->create(
            [
                'admin_id'=>$user->id,
                'user_name'=>$user->username,
                'ip'=>$request->getClientIp(),
                'login_location'=>"中国,天津",
                'browser'=>"chrome",
                'os'=>"MAC",
                'state'=>1,
                'msg'=>""
            ]
        );
        return ajax_output(200,"成功",['token'=>$token]);
    }


    /**
     * 退出登录
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        if(auth('box_admin')->user()){
            auth('box_admin')->logout();
        }
        return ajax_output(200,"成功");
    }
}
